package com.example.blog.controller;

import com.example.blog.constant.Constants;
import com.example.blog.model.BlogInfo;
import com.example.blog.service.BlogService;
import com.example.blog.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    private BlogService blogService;

    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    public List<BlogInfo> getList() {
        log.info("获取博客列表..");
        return blogService.getList();
    }

    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(Integer blogId, HttpServletRequest request) {
        log.info("根据博客id, 获取博客详情, blogId:{}",blogId);
        BlogInfo blogDetail = blogService.getBlogDetail(blogId);
        //判断作者是否为登录用户
        //获取登录用户
        //获取token
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        //从token中获取登录用户信息
        Integer userId = JwtUtils.getIdByToken(token);
        if(userId!=null && userId == blogDetail.getUserId()) {
            blogDetail.setIsLoginUser(true);
        }else {
            blogDetail.setIsLoginUser(false);
        }

        return blogDetail;
    }

    @RequestMapping("/add")
    public Boolean addBook(@RequestBody BlogInfo blogInfo, HttpServletRequest request) {
        log.info("添加博客,blogInfo:{}",blogInfo);
        //参数校验
        if(!StringUtils.hasLength(blogInfo.getTitle()) || !StringUtils.hasLength(blogInfo.getTitle())) {
            return false;
        }
        //获取登录用户
        //获取token
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        //从token中获取登录用户信息
        Integer userId = JwtUtils.getIdByToken(token);
        if(userId == null || userId <=0) {
            return false;
        }
        blogInfo.setUserId(userId);
        return blogService.insertBlog(blogInfo);
    }

    @RequestMapping("/update")
    public Boolean update(BlogInfo blogInfo) {
        log.info("更新博客, blogInfo:{}",blogInfo);
        //参数校验
        if(blogInfo.getId() == null
                || !StringUtils.hasLength(blogInfo.getTitle())
                ||!StringUtils.hasLength(blogInfo.getContent())) {
            return false;
        }
        blogService.update(blogInfo);
        return true;
    }

    @RequestMapping("/delete")
    public Boolean delete(Integer blogId) {
        log.info("删除博客 blogId:{}",blogId);
        if(blogId <= 0) {
            return false;
        }
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setId(blogId);
        blogInfo.setDeleteFlag(1);
        blogService.update(blogInfo);
        return true;
    }
}
